home *** CD-ROM | disk | FTP | other *** search
- Path: hubcap.clemson.edu!hubcap!mjs
- From: mjs@hubcap.clemson.edu (M. J. Saltzman)
- Newsgroups: comp.lang.c
- Subject: Re: Settle a bet please
- Date: 29 Mar 96 14:59:28 GMT
- Organization: Clemson University
- Message-ID: <mjs.828111568@hubcap>
- References: <4jfopb$o9n@news1.sympatico.ca> <KASPER.96Mar29073654@acm.org>
- NNTP-Posting-Host: hubcap.clemson.edu
- X-Newsreader: NN version 6.5.0 #1
-
- kasperowski@acm.org writes:
-
- >In article <4jfopb$o9n@news1.sympatico.ca> Gisele Swinson <gisele.swinson@sympatico.ca> writes:
-
- > | In C language, how do they calculate the length of an array.
- > |
- > | example
- > |
- > | To declare a string "My Name"
- > |
- > | is it char name[7] = "My Name"
- > | or
- > | is it chat Name[8] = "My Name"
-
- > char Name[8] = "My Name";
-
- >is correct. There's a \0 at the end of "My Name".
-
- > char Name[] = "My Name";
-
- >is better; the compiler does the counting for you.
-
- Actually, all three are correct, they just mean different things. First,
-
- char name[] = "My name";
-
- and
-
- char name[8] = "My name";
-
- do mean the same thing: reserve 8 chars and initialize them to contain
-
- {'M', 'y', ' ', 'n', 'a', 'm', 'e', '\0'}.
-
- This means that name[] can be treated as a "C string" (i.e., a
- null-terminated string) and used with the C string and i/o library
- routines that understand about null-terminated strings.
-
- But
-
- char name[7] = "My name";
-
- reserves 7 chars, and initializes them to contain
-
- {'M', 'y', ' ', 'n', 'a', 'm', 'e'}.
-
- This is perfectly legal C, but the resulting array of characters is
- not a "C string" and can't be used with the C library functions that
- understand null-terminated strings. It can still be used with the mem*
- functions, which require that the length of the arguments be passed
- as an argument.
-
- Caveats:
- (1) This may be different in C++. If you want to know about C++,
- post in comp.lang.c++.
-
- (2) Of course, we've said nothing about
-
- char *name = "My name";
-
- If you want to know about that, see the FAQ.
-
- --
- Matthew Saltzman
- Clemson University Math Sciences
- mjs@clemson.edu
-